<template>
  <div class="list-wapper">
    <div class="query__top">
      <el-row :gutter="20">
        <el-col :span="8">
          <span class="query__label">用户ID：</span>
          <el-input v-model="query.playerId" class="query-input" placeholder="请输入用户ID"/>
        </el-col>
        <el-col :span="8">
          <span class="query__label">用户昵称：</span>
          <el-input v-model="query.playerName" class="query-input" placeholder="请输入用户昵称"/>
        </el-col>
        <el-col :span="8">
          <span class="query__label">用户状态：</span>
          <el-select v-model="query.playerCtlState" class="query-input" placeholder="请选择状态">
            <el-option
              v-for="(item, index) in PlayerStatusOptions"
              :value="item.value"
              :label="item.label"
              :key="index"
            />
          </el-select>
        </el-col>
      </el-row>
      <el-row :gutter="20" class="mt-20">
        <el-col :span="10">
          <span class="query__label">注册时间：</span>
          <el-date-picker
            v-model="timeLimit"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"/>
        </el-col>
      </el-row>
      <el-row :gutter="20" class="button-content">
        <!-- <el-col :span="6"/> -->
        <el-col :span="6" :offset="18" class="query__right-content">
          <el-button size="small" type="primary" @click="handleSelect">查询</el-button>
          <el-button size="small" @click="handleReset">重置</el-button>
        </el-col>
      </el-row>
    </div>

    <el-table v-loading="loading" :data="list" size="small" style="width: 100%">
      <el-table-column prop="playerId" label="用户ID" width="150"/>
      <el-table-column prop="username" label="用户信息">
        <template slot-scope="{row}">
          <img :src="row.playerIcon"><span>{{ row.playerName }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="roomCard" label="用户房卡" width="120"/>
      <el-table-column prop="gold" label="用户金币" width="120"/>
      <el-table-column prop="createTime" label="注册时间" width="180">
        <template slot-scope="{row}">
          <span>{{ row.createTime | formatTimeByTimeS }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template slot-scope="scope">
          {{ scope.row.playerCtlState | playerStatusFormat }}&nbsp;&nbsp;
          <AsyncSwitch
            :before-change-sync-other-params="[scope.row]"
            :before-change-sync="changeStatus"
            v-model="scope.row.playerCtlState"
            :inactive-value="0"
            :active-value="1" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click.native.prevent="handleRechargeMoney(scope.row)"
          >充值</el-button>
          <el-button
            type="text"
            size="small"
            @click.native.prevent="handleSetOrCancelOwerGroup({ playerId: scope.row.playerId, status: 1 })"
          >设为群主</el-button>
          <el-button
            type="text"
            size="small">
            <router-link :to="{ name:'CustomerDetail', query: { playerId: scope.row.playerId } }">查看详情</router-link>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-if="totalCount && totalCount > 0" class="list-pagaps">
      <el-pagination
        :current-page="query.pageIndex || 1"
        :page-sizes="PageSizeArr"
        :page-size="pageOffset"
        :total="totalCount"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"/>
      <div/>
    </div>

    <RechargeDialog
      v-if="rechargeDialogShow"
      :player-id="activePlayerId"
      @close="rechargeDialogClose"
      @success="_loadData"
    />
  </div>

</template>
<script>
import { cloneDeep } from 'lodash'
import ErrorView from '@/components/ErrorView/index'
import LoadingView from '@/components/LoadingView/index'
import AsyncSwitch from '@/components/AsyncSwitch/index'
import { PLAYER_STATUS, PAGE_SIZE_ARR } from '@/common/dictory'
import { getPlayerList, changePlayerStatus, setOwerGroup } from '@/api/customer'
import { parseTime } from '@/utils'
import RechargeDialog from './_partials/recharge-dialog'
const QueryInitValue = {
  playerId: '',
  playerName: '',
  playerCtlState: '',
  startTime: '',
  endTime: '',
  pageIndex: 1
}
export default {
  name: 'CustomerManage',
  components: { ErrorView, LoadingView, AsyncSwitch, RechargeDialog },
  filters: {
    formatTimeByTimeS(timeStr) {
      return parseTime(new Date(timeStr), '{y}/{m}/{d} {h}:{i}:{s}')
    }
  },
  data() {
    return {
      list: [],
      loading: true,
      loadFailed: false,
      query: cloneDeep(QueryInitValue),
      totalCount: 0,
      pageOffset: 10,
      timeLimit: [],
      rechargeDialogShow: false,
      activePlayerId: ''

    }
  },
  computed: {
    PlayerStatusOptions() {
      return cloneDeep(PLAYER_STATUS || [])
    },
    PageSizeArr() {
      return cloneDeep(PAGE_SIZE_ARR || [10, 20, 30, 40])
    }
  },
  created() {
    this._loadData()
  },
  methods: {
    handleSelect() {
      this._loadData()
    },
    handleReset() {
      this.query = cloneDeep(QueryInitValue)
      this.timeLimit = []
    },
    handleSizeChange(pageOffset = 10) {
      this.query.pageIndex = 1
      this.pageOffset = pageOffset
      this._loadData()
    },
    handleCurrentChange(pageIndex = 1) {
      this.query.pageIndex = pageIndex
      this._loadData()
    },
    handleRechargeMoney({ playerId }) {
      this.activePlayerId = playerId
      this.rechargeDialogShow = true
    },
    handleSetOrCancelOwerGroup({ playerId, status }) {
      this.$confirm(`${status === 1 ? '设置' : '取消'}当前用户为群主？`, '用户管理', {
        distinguishCancelAndClose: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        setOwerGroup({ id: playerId, status }, '操作失败').then(() => {
          this.$message({
            type: 'success',
            message: '操作成功'
          })
          this._loadData()
        }).catch(msg => {
          this.$message({
            type: 'error',
            message: msg
          })
        })
      }).catch(() => {

      })
    },
    rechargeDialogClose() {
      this.activePlayerId = ''
      this.rechargeDialogShow = false
    },
    changeStatus(nextStatus, status, { playerId: id = '' }) {
      return new Promise((resolve, reject) => {
        this.$confirm(`${status === 1 ? '停用' : '启用'}当前游戏用户？`, '用户管理', {
          distinguishCancelAndClose: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          changePlayerStatus({ id, status: nextStatus }, '操作失败').then(() => {
            resolve()
          }).catch(msg => {
            this.$message({
              type: 'error',
              message: msg
            })
            reject()
          })
        }).catch(() => {
          reject()
        })
      })
    },
    _loadData() {
      var { pageOffset = 10 } = this
      var [startTime, endTime] = this.timeLimit || ['', '']
      this.loading = true
      this.loadFailed = false
      this.list = []
      getPlayerList({
        ...this.query,
        offset: pageOffset,
        limit: this.query.pageIndex,
        startTime,
        endTime
      }).then(({ playerList: rows = [], pageInfo = {}}) => {
        var {
          totalCount = 0
        } = pageInfo || {}
        this.totalCount = totalCount
        this.loading = false
        this.loadFailed = false
        this.list = rows
      }).catch(() => {
        this.loading = false
        this.loadFailed = true
      })
    }
  }
}
</script>

<style lang="scss" scoped>
// @import url('~@styles/btn.scss');
.list-wapper {
  padding: 20px;
}
.query__top {
  padding-bottom: 20px;
}
.query-input {
  width: calc(100% - 100px);
}
.button-content {
  margin-top: 20px;
}
.query__right-content {
  text-align: right;
}
.list-pagaps{
    text-align: right;
    padding-top:20px;
}
.query__label{
    font-weight: 600;
}
.mt-20{
  margin-top:20px;
}
</style>

